<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <n-tabs type="line" animated>
        <n-tab-pane name="详情" tab="详情">
          <n-form
            :label-width="90"
            :model="formValue"
            :rules="rules"
            label-placement="top"
            ref="formRef"
          >
            <n-form-item label="名称" path="title">
              <n-input v-model:value="formValue.title" placeholder="输入名称" />
            </n-form-item>
            <n-form-item label="分类" path="type_id">
              <n-select v-model:value="formValue.type_id" :options="types" />
            </n-form-item>
            <n-form-item label="上架设置" path="status">
              <n-radio-group v-model:value="formValue.status" name="status">
                <n-space>
                  <n-radio :value="1">上架</n-radio>
                  <n-radio :value="0">下架</n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="标签" path="tag">
              <n-radio-group v-model:value="formValue.tag" name="tag">
                <n-space>
                  <n-radio value="最新">最新</n-radio>
                  <n-radio value="热门">热门</n-radio>
                  <n-radio value="精选">精选</n-radio>
                  <n-radio value="特惠">特惠</n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="售卖方式" path="shop_type">
              <n-radio-group v-model:value="formValue.shop_type" name="shop_type">
                <n-space>
                  <n-radio :value="1">免费</n-radio>
                  <n-radio :value="2">付费</n-radio>
                  <!-- <n-radio :value="3">加密</n-radio> -->
                  <!-- <n-radio :value="4">指定学员</n-radio> -->
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="排序" path="sort">
              <n-input-number v-model:value="formValue.sort" placeholder="课程排序" />
            </n-form-item>
            <n-form-item label="划线价格" path="original_price">
              <n-input-number
                v-model:value="formValue.original_price"
                :precision="2"
                placeholder="划线价格"
              />
            </n-form-item>
            <n-form-item label="价格" path="price">
              <n-input-number
                v-model:value="formValue.price"
                :precision="2"
                placeholder="课程价格"
              />
            </n-form-item>
            <n-form-item label="封面" path="cover">
              <BasicUpload
                :action="`${uploadUrl}`"
                :headers="uploadHeaders"
                :data="{ folder: 'course' }"
                name="files"
                :width="200"
                :height="150"
                :maxNumber="1"
                @upload-change="uploadChange"
                v-model:value="uploadList"
              />
            </n-form-item>
            <n-form-item label="介绍" path="content">
              <n-card :bordered="false" class="mt-4 proCard">
                <TEditor ref="editor" v-model="formValue.content" />
              </n-card>
            </n-form-item>
            <n-form-item>
              <n-space class="mt30">
                <n-button type="primary" @click="formSubmit">提交</n-button>
                <n-button @click="resetForm">重置</n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </n-tab-pane>
        <n-tab-pane name="目录" tab="目录">
          <n-space>
            <n-button @click="showModal = true">选择视频</n-button>
            <n-button @click="insertVideo">上传视频</n-button>
          </n-space>
          <n-data-table
            class="mt30"
            :columns="column_videos"
            :data="videos"
            :row-props="rowProps"
          />
        </n-tab-pane>
      </n-tabs>
    </n-card>

    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      title="选择视频"
      style="width: 600px"
    >
      <SelectVideo @on-select-video="onSelectVideo" />
    </n-modal>

    <n-modal v-model:show="showVideo" preset="dialog" title="选择视频" :mask-closable="false">
      <uploadSelectVideo :data="filesUrl" :id="id" @save-video="saveVideo" />
    </n-modal>

    <n-modal v-model:show="showVideoTitle" :show-icon="false" preset="dialog" title="视频课程名称">
      <n-form :model="videoInfo" ref="formRef" label-placement="left">
        <n-form-item label="名称" path="title">
          <n-input placeholder="请输入名称" v-model:value="videoInfo.title" />
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input placeholder="请输入排序" v-model:value="videoInfo.sort" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showVideoTitle = false)">取消</n-button>
          <n-button type="info" @click="onVideoTitle">确定</n-button>
          <n-popconfirm @positive-click="onVideoDelete">
            <template #trigger>
              <n-button type="error">删除</n-button>
            </template>
            确定要删除这个视频么
          </n-popconfirm>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref, reactive, onMounted, h } from 'vue';
  import { NButton, useMessage } from 'naive-ui';
  import { BasicUpload } from '@/components/Upload';
  import { useGlobSetting } from '@/hooks/setting';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import { getCourseInfo, patchCourse, putCourse } from '@/api/course/course';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useRouter } from 'vue-router';
  import { getType } from '@/api/type/type';
  import { useUser } from '@/store/modules/user';
  import SelectVideo from '@/components/selectVideo.vue';
  import uploadSelectVideo from '@/components/uploadSelectVideo.vue';
  import TEditor from '@/components/TEditor.vue';

  const id: any = ref(useRouter().currentRoute.value.params.id);
  const showModal = ref(false);
  const videos = ref<any>([]);
  const globSetting = useGlobSetting();
  const rules = {
    title: {
      required: true,
      message: '请输入课程名称',
      trigger: 'blur',
    },
    type_id: {
      type: 'number',
      required: true,
      message: '请输入选择分类',
      trigger: ['blur', 'change'],
    },
    cover: {
      required: true,
      message: '请上传封面',
      trigger: 'blur',
    },
  };

  let types = ref<any>([]);

  const formRef: any = ref(null);
  const message = useMessage();
  const { uploadUrl } = globSetting;

  const showVideo = ref(false);
  const filesUrl = ref([]);

  const defaultValueRef = () => ({
    id: 0,
    title: '',
    cover: [''],
    type_id: '',
    original_price: 0,
    price: 0,
    sort: 0,
    shop_type: 2,
    content: '',
    status: 1,
    tag: '',
    videos: '',
  });

  let formValue = reactive(defaultValueRef());
  const uploadList = ref([]);

  const uploadHeaders = reactive({
    platform: 'miniPrograms',
    timestamp: new Date().getTime(),
    Authorization: 'Bearer ' + useUser().getToken,
  });

  const getData = async () => {
    const response: any = await getCourseInfo(formValue.id);
    if (response.code === ResultEnum.SUCCESS) {
      response.data.sort = parseFloat(response.data.sort);
      response.data.price = parseFloat(response.data.price);
      response.data.original_price = parseFloat(response.data.original_price);
      response.data.status = parseInt(response.data.status);
      let cover: any = [];
      cover.push(response.data.cover);
      uploadList.value = cover;
      videos.value = response.videos;
      Object.assign(formValue, response.data);
    }
  };

  const getTypes = async () => {
    const response: any = await getType({ model: 'Course' });
    response.data.forEach((element: any) => {
      types.value.push({ label: element.title, value: element.id });
    });
  };

  function formSubmit() {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        try {
          formValue.videos = JSON.stringify(videos.value);
          let response: any = null;
          if (formValue.id == 0) {
            response = await putCourse(formValue);
          } else {
            response = await patchCourse(formValue);
          }

          if (response.code === ResultEnum.SUCCESS) {
            message.success(response.message);
          }
        } finally {
          // loading.value = false;
        }
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  function resetForm() {
    formRef.value.restoreValidation();
    formValue = Object.assign(unref(formValue), defaultValueRef());
  }

  function uploadChange(list: string[]) {
    let cover: any = unref(list);
    formValue.cover = cover[0];
  }

  const onSelectVideo = (data: any) => {
    videos.value.push(...data);
    showModal.value = false;
  };

  function insertVideo() {
    if (!formValue.id) {
      message.error('请先保存课程基本信息');
      return;
    }
    showVideo.value = true;
  }

  function saveVideo(data: any) {
    videos.value.push(...data);
    showVideo.value = false;
    getData();
  }

  onMounted(() => {
    formValue.id = id.value;
    if (formValue.id != 0) {
      getData();
    }
    getTypes();
  });

  const showVideoTitle = ref(false);
  interface RowData {
    id: number;
    title: string;
    duration: number;
    size: string;
    sort: number;
  }
  const videoInfo = ref<RowData>({
    id: 0,
    title: '',
    duration: 0,
    size: '',
    sort: 0,
  });

  function rowProps(row: RowData) {
    return {
      style: 'cursor: pointer;',
      onClick: () => {
        showVideoTitle.value = true;
        videoInfo.value = row;
      },
    };
  }

  function onVideoTitle() {
    videos.value.sort((a, b) => a.sort - b.sort);
    showVideoTitle.value = false;
  }

  const onVideoDelete = () => {
    let index = -1;
    videos.value.forEach((e: any, i: number) => {
      if (e.id == videoInfo.value.id) {
        index = i;
      }
    });
    if (index == -1) {
      return;
    }
    videos.value.splice(index, 1);
    showVideoTitle.value = false;
  };

  const column_videos = [
    {
      title: '视频名称',
      key: 'title',
    },
    {
      title: '时长',
      key: 'duration',
    },
    {
      title: '大小',
      key: 'size',
    },
    {
      title: '排序',
      key: 'sort',
      sorter: (row1, row2) => row1.sort - row2.sort,
    },
  ];
</script>

<style lang="less">
  .ql-toolbar.ql-snow {
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: 1px solid #eee;
    margin-top: -10px;
  }

  .ql-container.ql-snow {
    border: none;
  }
</style>
